package com.wxyzz.cem.config;

import com.wxyzz.cem.exception.ServiceException;
import com.wxyzz.cem.exception.SystemException;
import com.wxyzz.cem.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常配置
 *
 * @author xclhove
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * ExceptionHandler相当于controller的@RequestMapping,如果抛出的的是ServiceException，则调用该方法
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Result<Object> serviceExceptionHandler(HttpServletResponse response, ServiceException exception) {
        response.setContentType("application/json");
        return Result.error(exception.getCode(), exception.getMessage(), exception.getData());
    }
    
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<Object> exceptionHandler(HttpServletResponse response, Exception exception) {
        String message = exception.getMessage();
        exception.printStackTrace();
        log.error(message);
        return serviceExceptionHandler(response, new SystemException());
    }
}
